<template>
	<view class="container">
		<view class="form-container">
			<up-form :model="form" :rules="rules" ref="formRef" labelPosition="left" labelWidth="160rpx">
				<!-- 基本信息 -->
				<view class="form-section">
					<up-form-item :required="true" label="报修单号" prop="repair_code" class="border-bottom">
						<up-input v-model="form.repair_code" placeholder="系统自动生成" border="none" disabled></up-input>
					</up-form-item>
					<up-form-item :required="true" label="报修单名称" prop="repair_name" class="border-bottom">
						<up-input v-model="form.repair_name" placeholder="请输入报修单名称" border="none"></up-input>
					</up-form-item>
					<up-form-item :required="true" label="报修人" prop="repair_user" class="border-bottom"
						:key="itemKeys.repair_user" @click="
              user.show = true;
              hideKeyboard();
            ">
						<view @click.self="
                user.show = true;
                hideKeyboard();
              ">
							<up-input v-model="user.repair_user" placeholder="请选择报修人" border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right"></up-icon>
						</template>
					</up-form-item>

					<up-form-item label="报修日期" prop="repair_date" class="border-bottom" @click="
              datePicker.show = true;
              datePicker.type = '0';
              hideKeyboard();
            ">
						<view @click.self="
                showDatePicker = true;
                datePicker.type = '0';
                hideKeyboard();
              ">
							<up-input v-model="form.repair_date" placeholder="请选择日期" border="none">
							</up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right"></up-icon>
						</template>
					</up-form-item>
					<up-form-item label="期望修复日期" prop="expect_repair_date" class="border-bottom" @click="
              datePicker.show = true;
              datePicker.type = '1';
              hideKeyboard();
            ">
						<view @click.self="
                showDatePicker = true;
                datePicker.type = '1';
                hideKeyboard();
              ">
							<up-input v-model="form.expect_repair_date" placeholder="请选择日期" border="none">
							</up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right"></up-icon>
						</template>
					</up-form-item>
				</view>
				<!-- 故障说明 -->
				<view class="form-section">
					<view class="section-title">
						<text class="asterisk">*</text>故障说明
					</view>
					<up-form-item prop="fault_description" :key="itemKeys.fault_description">
						<up-textarea v-model="form.fault_description" placeholder="请输入故障说明"></up-textarea>
					</up-form-item>
				</view>
				<!-- 附件 -->
				<view class="form-section">
					<view class="section-title">附件</view>
					<up-button type="primary" @click="selectFile">点击上传文件</up-button>
					<!-- 已选文件展示 -->
					<view v-if="attachmentsUpload[0].files.length" style="margin-top: 10rpx">
						<view v-for="items in attachmentsUpload[0].files" :key="items.id" class="file-item">
							<text class="file-name" @click="handleDownFile(items)">{{items.name}}</text>
							<up-icon @click="handleClose(items)" name="close" color="#ccc" class="file-close" />
						</view>
					</view>
					<!-- 					<up-form-item prop="attachment">
						<up-upload style="margin-top: 20rpx" :fileList="fileList" @afterRead="afterRead" @delete="deletePic"
							name="attachment" :maxCount="1" :maxSize="2 * 1024 * 1024" width="250" height="150"
							previewFullImage></up-upload>
					</up-form-item> -->
				</view>
			</up-form>
			<!-- 资产列表 -->
			<view class="asset-list">
				<view class="list-header">
					<text>资产列表</text>
					<text class="count">共计: {{ assetDataList.length }}</text>
				</view>

				<view class="asset-item" v-for="item in assetDataList" :key="item.id">
					<!-- 左侧信息 -->
					<view class="asset-right-container">
						<up-image :src="getImage(item.image)" width="160rpx" height="160rpx" />
						<view class="status">
							<up-tag v-if="item.asset_state_name" :text="item.asset_state_name" size="mini" />
						</view>
					</view>
					<view class="asset-info">
						<view class="asset-name">{{ item.asset_name }}</view>
						<view class="info">使用部门：{{ item.department_name }}</view>
						<view class="info">资产管理员：{{ item.asset_admin_name }}</view>
						<view class="info">存放地点：{{ item.location_name }}</view>
						<view class="info">资产编码：{{ item.asset_code }}</view>
						<view class="info">RFID编码：{{ item.label_number }}</view>
					</view>
					<up-icon name="minus-circle" size="22" v-if="!pageDisabled" color="#f00" @click="handleDelete(item)" />
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="footer" style="display: flex">
			<up-button type="primary" text="添加" @click="addAssetList"></up-button>
			<up-button type="primary" text="提交" @click="submitForm" style="margin-left: 2px"></up-button>
		</view>

		<!-- 日期选择器 -->
		<up-datetime-picker :show="datePicker.show" mode="date" v-model="dateTime" closeOnClickOverlay
			@confirm="confirmDate" @cancel="datePickerClose" @close="datePickerClose"
			:formatter="formatter"></up-datetime-picker>
		<!-- 选人 -->
		<up-action-sheet :show="user.show" :actions="user.actions" title="请选择" @close="user.show = false"
			@select="userSelect">
		</up-action-sheet>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onBeforeUnmount
	} from "vue";
	import {
		onLoad,
		onUnload
	} from "@dcloudio/uni-app";
	import {
		generateUUID,
		formatter,
		formatDateTime
	} from "@/utils";
	import http, {
		BASE_URL
	} from "@/api/request";
	import {
		t
	} from "@/locale/index.js";
	import fileSys from "@/utils/fileSys";

	const formRef = ref(null);
	const datePicker = reactive({
		type: "0",
		show: false,
	});

	const topOffset = ref(0);
	const pageType = ref("");
	const assetDataList = ref([]);
	const attachmentsUpload = ref([{
		Fileld: [],
		files: [],
		linkId: "1",
		taskId: "<%assetrepairmstr.id%>",
	}, ]);
	const pageId = ref("");

	onLoad(async (query) => {
		await getPickerDataList();
		const info = uni.getSystemInfoSync();

		const statusBarHeight = info.statusBarHeight || 0;
		const navBarHeight = 44; // 通常为 44 px
		topOffset.value = statusBarHeight + navBarHeight;
		if (query.type === "add") {
			uni.setNavigationBarTitle({
				title: t("assetWarranty.add"),
			});
		} else if (query.type === "edit") {
			const data = uni.getStorageSync("assetWarrantyData");
			uni.setNavigationBarTitle({
				title: t("assetWarranty.edit"),
			});
			form.value = data;
			await getCurrAssetList();
			user.repair_user = user.actions.find(
				(item) => item.value === data?.repair_user
			)?.name;
		}
		pageType.value = query.type;

		if (form.value.id) {
			await getFiles();
		}
		// 获取页面信息
		await getPageInfo();
	});

	const itemKeys = reactive({
		repair_user: Date.now(),
		fault_description: Date.now() + 1,
	});

	onUnload(() => {
		uni.removeStorageSync("assetWarrantyData");
	});

	const getPickerDataList = async () => {
		const data = {
			code: "Sys_GetUserNameById",
			filters: [],
			allColumnFilter: true,
			tableFilters: [],
		};

		try {
			const {
				code,
				isSuccess,
				result
			} = await http.post("/api/module/GetViewTable", data)
			if (code && isSuccess) {
				user.actions = result.viewTable.map((item) => {
					return {
						...item,
						name: item.text,
						value: item.id,
					};
				});
			}

		} catch (error) {
			console.error("获取用户列表失败:", error);
		}
	};
	let oldData = [];
	const getCurrAssetList = async () => {
		const data = {
			code: "getAssetListByRepairCode",
			filters: [{
				name: "repair_code",
				value: form.value.repair_code,
			}, ],
			allColumnFilter: true,
			tableFilters: [],
			pageInput: {
				currentPage: 1,
				pageSize: 999,
			},
			permissionKey: "",
		};

		http
			.post("/api/module/GetViewTable", data)
			.then((res) => {
				if (res.isSuccess && res.result && res.result.viewTable) {
					assetDataList.value = res.result.viewTable;
					oldData = assetDataList.value.map(item => ({
						...item
					}));
				}
			})
			.catch((err) => {
				console.error("获取报修列表失败:", err);
				uni.showToast({
					title: "获取报修列表失败",
					icon: "none",
				});
			});
	};

	onMounted(() => {
		uni.$on("assetSelected", handleAssetSelected);
	});

	onBeforeUnmount(() => {
		uni.$off("assetSelected", handleAssetSelected);
	});

	const getImage = (image) => {
		const type = getItemType(image);
		if (image) {
			if (type === "ID") {
				return `${BASE_URL}/File/GetImage?fileId=${image}`;
			} else {
				return image;
			}
		}
		return "";
	};

	const getItemType = (item) => {
		const idPattern = /^[a-zA-Z0-9-]+$/; // 包含字母、数字和 - 符号
		const apiPattern = /^\/File\//; // 假设接口地址以 '/File/' 开头
		const pathPattern = /^\/(?!File)/; // 普通路径以 '/' 开头，但不以 '/File/' 开头
		const relativePathPattern = /^[^/]/; // 假设相对路径不以 '/' 开头

		if (idPattern.test(item)) {
			return "ID";
		} else if (apiPattern.test(item)) {
			return "接口"; // 识别接口地址
		} else if (pathPattern.test(item)) {
			return "路径"; // 识别普通路径
		} else if (relativePathPattern.test(item)) {
			return "相对路径"; // 识别相对路径
		} else {
			return "其他";
		}
	};

	const selectFile = () => {
		if (attachmentsUpload.value[0].files.length === 10) {
			uni.showLoading({
				title: "超出限制！",
				type: "error",
			});
		} else {
			fileSys().then((res) => {
				console.log("date=" + formatDateTime(new Date()), )
				const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
				attachmentsUpload.value[0].files.push({
					id: res[0].id,
					name: (res[0].fileName || "未知文件") +
						"  " +
						userInfo.name +
						"  " +
						formatDateTime(new Date()),
					url: `/File/Download?fileId=` + res[0].id,
				});
			});
		}
		setTimeout(() => {
			uni.hideLoading();
		}, 1500);
	};

	const handleDownFile = (items) => {
		uni.downloadFile({
			url: BASE_URL + items.url,
			success: (res) => {
				if (res.statusCode === 200) {
					plus.runtime.openFile(res.tempFilePath, {}, (e) => {
						uni.showModal({
							title: "无法打开文件",
							content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
							confirmText: "去安装",
							success: (modalRes) => {
								if (modalRes.confirm) {
									try {
										plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
											plus.runtime.openURL('https://browser.qq.com');
										});
									} catch (e) {
										plus.runtime.openURL('https://browser.qq.com');
									}
								}
							},
						});
					});
				}
			},
			fail: (err) => {
				console.error("下载失败", err);
				uni.showToast({
					title: "下载失败",
					icon: "none"
				});
			},
		});
	};

	const getFiles = async () => {
		const postData = {
			linkId: "1",
			taskId: form.value.id,
		};
		const {
			code,
			isSuccess,
			result
		} = await http.post(
			"/api/file/GetTaskLinkedFiles",
			postData
		);
		if (code && isSuccess && result) {
			result.forEach((item) => {
				attachmentsUpload.value[0].files.push({
					id: item.id,
					name: item.fileName + "  " + item.userName + "  " + item.creationTime,
					url: `/File/Download?fileId=` + item.id,
				});
			});
		}
	};

	const handleClose = (items) => {
		attachmentsUpload.value[0].files = attachmentsUpload.value[0].files.filter(
			(item) => item.id !== items.id
		);
	};

	const getPageInfo = async () => {
		const data = {
			assetlist: "assetwarranty",
			pageCode: "assetwarrantyadd",
		};

		const {
			code,
			isSuccess,
			result
		} = await http.post(
			"/api/page/GetPageInfoByCode",
			data
		);
		if (code && isSuccess) {
			pageId.value = result.page.parentPageId;
		}
	};

	const handleAssetSelected = (data) => {
		data.forEach((item) => {
			const isDuplicate = assetDataList.value.some(
				(existingItem) => existingItem.id === item.id
			);
			if (!isDuplicate) {
				assetDataList.value.push(item);
			}
			console.log("itenmdara=" + JSON.stringify(item))
		});

	};


	const handleDelete = (item) => {
		assetDataList.value = assetDataList.value.filter(
			(items) => item.id !== items.id
		);
	};

	const addAssetList = () => {
		uni.navigateTo({
			url: "/components/assetsAddList/index?type=warranty",
		});
	};

	const attachment = ref([]);
	const maxSize = 10 * 1024 * 1024; // 10MB
	const maxCount = 10;
	const allowedExts = [
		"png",
		"jpg",
		"jpeg",
		"pdf",
		"txt",
		"doc",
		"docx",
		"xls",
		"xlsx",
	];

	const form = ref({
		id: "",
		repair_code: "",
		repair_name: "",
		repair_date: new Date().toISOString().split("T")[0],
		expect_repair_date: "",
		user: "",
		repair_user: "",
		fault_description: "",
		attachment: "",
	});

	const rules = {
		repair_name: {
			type: "string",
			required: true,
			message: "请输入保修单名称",
			trigger: ["blur", "change"],
		},
		fault_description: {
			type: "string",
			required: true,
			message: "请输入故障说明",
			trigger: ["blur", "change"],
		},
		repair_user: {
			type: "string",
			required: true,
			message: "请选择报修人",
			trigger: ["blur", "change"],
		},
	};

	const dateTime = ref(Number(new Date()));

	const hideKeyboard = () => {
		uni.hideKeyboard();
	};

	const user = reactive({
		show: false,
		repair_user: "",
		actions: [],
	});

	const userSelect = (e) => {
		form.value.repair_user = e.value;
		user.repair_user = e.name;
		formRef.value.validateField("repair_user");
	};

	// 日期选择
	const confirmDate = (e) => {
		datePicker.show = false;
		if (datePicker.type == "0") {
			form.value.repair_date = result(e.value, e.mode);
		} else if (datePicker.type == "1") {
			form.value.expect_repair_date = result(e.value, e.mode);
		}
	};

	const result = (time, mode) => {
		const timeFormat = uni.$u.timeFormat;
		return timeFormat(time, "yyyy-mm-dd");
	};

	const datePickerClose = () => {
		datePicker.show = false;
	};

	// 切换标签页
	const changeTab = (value) => {
		currentTab.value = value.index;
	};

	const getDeletedAssets = () => {
		if (pageType.value !== "edit") return [];

		return oldData.filter(originalItem =>
			!assetDataList.value.some(currentItem =>
				currentItem.id === originalItem.id
			)
		);
	};

	// 提交表单
	const submitForm = () => {
		let reqData;
		formRef.value
			.validate()
			.then(() => {
				uni.showLoading({
					title: "提交中...",
				});
				if (pageType.value === "add") {
					if (form.value.id) {
						delete form.value.id;
					}
					if (form.value.repair_code) {
						delete form.value.repair_code;
					}
				}

				const rawData = {
					...form.value,
					attachment: attachmentsUpload.value?.[0]?.files?.length ?
						attachmentsUpload.value[0].files.map((item) => item.id).join(",") : "",
				};

				const dataObjct = Object.fromEntries(
					Object.entries(rawData).filter(
						([_, value]) => value !== "" && value !== null && value !== undefined
					)
				);
				dataObjct.repair_state = 'PENDING_REVIEW';
				if (pageType.value === "add") {
					let filteredAssets = [];
					if (
						assetDataList &&
						assetDataList.value.length &&
						assetDataList.value.length >= 0
					) {
						filteredAssets = assetDataList.value.filter(item =>
							!item.repair_code || item.repair_code.trim().toLowerCase() === "null"
						);
						filteredAssets.forEach(asset => {
							asset.old_asset_state = asset.asset_state;
						});
						assetDataList.value.forEach(asset => {
							asset.old_asset_state = asset.asset_state;
						});
					}
					reqData = {
						pageId: pageId.value,
						methodName: "doSaveTableData",
						saveTableDataRequest: {
							"data": {
								insert: {
									assetrepairmstr: {
										"data": dataObjct,
									},
									assetrepairdet: {
										"data": filteredAssets,
									}
								},
								update: {},
								remove: {},
								updateWhere: {},
								removeWhere: {},
								otherData: {
									fileAttachments: attachmentsUpload.value,
								},
								savedInvoke: {},
								pageAuths: [],
							},
						},
					};
				} else if (pageType.value === "edit") {
					let filteredAssets = [];
					if (
						assetDataList &&
						assetDataList.value.length &&
						assetDataList.value.length >= 0
					) {
						filteredAssets = assetDataList.value.filter(item =>
							!item.repair_code || item.repair_code.trim().toLowerCase() === "null"
						);
						filteredAssets.forEach(asset => {
							asset.old_asset_state = asset.asset_state;
						});
					}

					const deletedAssets = getDeletedAssets();
					reqData = {
						pageId: pageId.value,
						methodName: "doSaveTableData",
						saveTableDataRequest: {
							"data": {
								insert: {
									assetrepairdet: {
										"data": filteredAssets
									},
								},
								update: {
									assetrepairmstr: {
										"data": dataObjct,
									},
									assetrepairdet: {
										"data": deletedAssets.map(item => ({
											id: item.id,
											is_deleted: 1
										})),
									},
								},
								remove: {},
								updateWhere: {},
								removeWhere: {},
								otherData: {
									fileAttachments: attachmentsUpload.value,
								},
								savedInvoke: {},
								pageAuths: [],
							},
						},
					};
				}

				console.log("提交qiandata=" + JSON.stringify(reqData));
				http.post("/api/module/Invoke", reqData).then((res) => {
					if (res.code && res.isSuccess) {
						console.log("提交成功");
						uni.hideLoading();
						uni.showToast({
							title: "提交成功",
							icon: "success"
						});

						// 报修后更新资产状态为"REPAIRING"
						if (
							reqData.saveTableDataRequest?.data?.insert?.assetrepairdet?.data &&
							reqData.saveTableDataRequest.data.insert.assetrepairdet.data.length > 0
						) {
							changeAssetState(
								reqData.saveTableDataRequest.data.insert.assetrepairdet.data.map(item => item.asset_code),
								"REPAIRING"
							);
						}
						// 删除明细的还原资产 old_asset_state
						if (deletedAssets.length > 0) {
							const statusGroupMap = {};
							deletedAssets.forEach(item => {
								if (item.asset_code) {
									const status = item.old_asset_state || 'IDLE';
									if (!statusGroupMap[status]) {
										statusGroupMap[status] = [];
									}
									statusGroupMap[status].push(item.asset_code);
								}
							});

							for (const [state, codes] of Object.entries(statusGroupMap)) {
								changeAssetState(codes, state);
							}
						}
					} else {
						console.log("提交失败，res=" + JSON.stringify(res));
					}
					if (pageType.value === "add") {
						formRef.value?.resetFields(); // 重置校验状态
						form.value = {
							id: "",
							repair_code: "",
							repair_name: "",
							repair_date: new Date().toISOString().split("T")[0],
							expect_repair_date: "",
							user: "",
							repair_user: "",
							fault_description: "",
							attachment: "",
						};
						user.repair_user = "";
						assetDataList.value = [];
						oldData = [];
						attachmentsUpload.value = [{
							Fileld: [],
							files: [],
							linkId: "1",
							taskId: "<%assetrepairmstr.id%>",
						}, ];
					}
					itemKeys["repair_user"] = Date.now();
					itemKeys["fault_description"] = Date.now() + 1;

					setTimeout(() => {
						goBack();
					}, 1500);
				});
			})
			.catch((err) => {
				console.error("表单验证失败:", err);
			});
	};

	const changeAssetState = (codes, state) => {
		let req = {
			interfaceCode: "Assetlist.doUpdateStatusByAssetCodes",
			asset_state: state,
			asset_codes: codes
		};
		http.post("/api/module/Invoke", req).then((res) => {
			if (res.code && res.isSuccess) {
				console.log("资产状态修改成功！")
			}
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};
</script>
<style lang="scss" scoped>
	.container {
		padding-bottom: 100rpx;
		background-color: #f7f7f7;
	}

	.form-container {
		padding: 20rpx 30rpx;
	}

	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 0 20rpx;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		padding: 24rpx 0;
		color: #333;
		border-bottom: 1rpx solid #f5f5f5;
	}

	/* 新增样式 */
	.file-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.file-name {
		color: red;
		font-size: 15px;
		flex: 1;
		word-break: break-all;
		/* 允许单词内换行 */
		white-space: normal;
		/* 默认行为，允许换行 */
	}

	.file-close {
		margin-left: 20rpx;
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	:deep(.up-form-item__body) {
		padding: 20rpx 0;
	}

	:deep(.up-form-item__body__left__content) {
		font-size: 28rpx;
		color: #666;
	}

	:deep(.up-form-item__body__right__content) {
		flex: 1;
		text-align: right;
	}

	:deep(.up-input__content__field-wrapper__field) {
		text-align: right;
	}

	.codePlaceholder {
		color: #000 !important;
	}

	.border-bottom {
		border-bottom: 1px solid #f5f5f5;
	}

	.asterisk {
		color: red;
	}

	.asset-list {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;

		.list-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 20rpx;
		}

		.asset-item:last-child {
			padding-bottom: 0;
		}

		.asset-item {
			display: flex;
			// align-items: center;
			justify-content: space-between;
			border-top: 1px solid #eee;
			padding: 20rpx 0;

			.asset-right-container {
				position: relative;

				.status {
					position: absolute;
					right: 0;
					top: 0;
				}
			}

			// .status {
			//   background-color: #4caf50;
			//   color: #fff;
			//   padding: 4rpx 12rpx;
			//   border-radius: 8rpx;
			//   font-size: 22rpx;
			// }

			.asset-info {
				flex: 1;
				padding-left: 20rpx;

				.asset-name {
					font-weight: bold;
					font-size: 28rpx;
					margin-bottom: 6rpx;
				}

				.info {
					color: #666;
					font-size: 24rpx;
				}
			}
		}
	}
</style>